package com.example.springcloud.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import com.example.springcloud.domain.UserInfo;
import com.example.springcloud.request.LoginRequest;
import com.example.springcloud.request.UserRegisterDto;
import com.example.springcloud.utils.WechatUtil;
import com.ruoyi.common.annotation.Anonymous;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.example.springcloud.service.IUserInfoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户信息Controller
 *
 * @author 经纬线
 * @date 2024-03-04
 */
@RestController
@RequestMapping("/jiu-mount-huangshan/user_info")
@Api(tags = "用户信息管理")
public class UserInfoController extends BaseController {
    @Autowired
    private IUserInfoService userInfoService;

    /**
     * 查询用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:user_info:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserInfo userInfo) {
        startPage();
        List<UserInfo> list = userInfoService.selectUserInfoList(userInfo);
        return getDataTable(list);
    }

    /**
     * 导出用户信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:user_info:export')")
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UserInfo userInfo) {
        List<UserInfo> list = userInfoService.selectUserInfoList(userInfo);
        ExcelUtil<UserInfo> util = new ExcelUtil<UserInfo>(UserInfo.class);
        util.exportExcel(response, list, "用户信息数据");
    }

    /**
     * 获取用户信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user_info:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        return success(userInfoService.selectUserInfoByUserId(userId));
    }

    /**
     * 新增用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:user_info:add')")
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody UserInfo userInfo) {
        return toAjax(userInfoService.insertUserInfo(userInfo));
    }

    /**
     * 修改用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:user_info:edit')")
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UserInfo userInfo) {
        return toAjax(userInfoService.updateUserInfo(userInfo));
    }

    /**
     * 删除用户信息
     */
    @PreAuthorize("@ss.hasPermi('system:user_info:remove')")
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userInfoService.deleteUserInfoByUserIds(userIds));
    }

    // 外部接口
    @Anonymous
    @ResponseBody
    @GetMapping(value = "/info")
    public AjaxResult info() {
        List<UserInfo> info = userInfoService.listinfo();
        return AjaxResult.success("info", info);
    }


    /**
     * 登陆验证
     *
     * @param loginRequest 登录请求对象
     * @return 验证信息
     */
    // TODO 缺少密码加密
    @Anonymous
    @ResponseBody
    @RequestMapping(value = "/userLogin", produces = {"application/json;charset=utf-8"}, method = RequestMethod.POST)
    @ApiOperation(value = "用户登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "userPassword", value = "用户密码", required = true, dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "登陆成功")})
    public AjaxResult userLogin(@RequestBody LoginRequest loginRequest,
                                HttpServletResponse response) {
        System.out.println(loginRequest.getUsername());

        UserInfo userInfo = userInfoService.getUserByUserName(loginRequest.getUsername());
        if (userInfo != null && userInfo.getUserPassword().equals(loginRequest.getUserPassword())) {
            userInfo.setUserPassword(null); // 登陆成功后不返回password字段

            // 生成 Token
            String token = generateToken(userInfo);

            // 将 Token 存储在 Cookie 中
            Cookie cookie = new Cookie("token", token);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);
//            System.out.println(token);
//            System.out.println(cookie);

            return AjaxResult.success("登陆成功！", userInfo);
        } else if (userInfo != null && !userInfo.getUserPassword().equals(loginRequest.getUserPassword())) {
            return AjaxResult.success("登陆失败！", "密码错误！");
        }
        // TODO 修改返回结果为AjaxResult.error()
        // 无该用户
        return AjaxResult.error("登陆失败！", "无该用户");
    }

    private String generateToken(UserInfo userInfo) {
        // 根据用户信息生成 token
        String token = Jwts.builder()
                .setSubject(userInfo.getUsername())
                .setExpiration(new Date(System.currentTimeMillis() + 3600000)) // 设置过期时间为1小时
                .signWith(SignatureAlgorithm.HS512, "lmy3130056596")
                .compact();
        return token;
    }

    /**
     * // 用户注册接口
     *
     * @param userRegisterDto 用户注册信息
     * @return 注册结果
     */
    @ResponseBody
    @RequestMapping(value = "/userRegister", produces = {"application/json;charset=utf-8"}, method = RequestMethod.POST)
    @ApiOperation(value = "用户注册接口")
    @ApiResponses({@ApiResponse(code = 200, message = "注册成功")})
    public AjaxResult userRegister(@RequestBody UserRegisterDto userRegisterDto) {
        // 根据用户名查询用户是否已存在
        UserInfo existingUser = userInfoService.getUserByUserName(userRegisterDto.getUsername());
        if (existingUser != null) {
            return AjaxResult.error("用户名已被注册，请更换用户名");
        }
        // 创建新用户信息
        UserInfo newUser = new UserInfo();
        newUser.setUsername(userRegisterDto.getUsername());
        newUser.setUserPassword(userRegisterDto.getUserPassword());
        newUser.setEmail(userRegisterDto.getEmail());
        newUser.setGender(userRegisterDto.getGender());
        newUser.setPhoneNumber(userRegisterDto.getPhoneNumber());
        newUser.setAvatar("");
        newUser.setNickname("默认用户");

        // 其他用户信息赋值，如头像、昵称等
//    System.out.println(newUser);
        // 调用服务层完成用户注册
        boolean success = userInfoService.registerUser(newUser);
        if (success) {
            return AjaxResult.success("注册成功！");
        } else {
            return AjaxResult.error("注册失败，请稍后重试");
        }
    }


    // 用户修改基本资料信息
    @Anonymous
    @ResponseBody
    @RequestMapping(value = "/userModifiesInfo", produces = {"application/json;charset=utf-8"})
    @ApiOperation(value = "修改用户信息")
    public AjaxResult userModifiesInfo(@RequestBody UserInfo userInfo) {
        return toAjax(userInfoService.updateUserInfo(userInfo));
    }

    /**
     * 获取openid
     *
     * @param code
     */
    @Anonymous
    @ResponseBody
    @RequestMapping(value = "/getOpenid", produces = {"application/json;charset=utf-8"}, method = RequestMethod.POST)
    @ApiOperation(value = "获取openid接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "微信小程序code", required = true, dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 200, message = "获取成功")})
    public AjaxResult getOpenid(@RequestParam("code") String code) {
        // 根据code获取openid
        String openid = WechatUtil.getOpenId(code);
        if (openid != null) {
            return AjaxResult.success("获取成功！", openid);
        } else {
            return AjaxResult.error("获取失败！");
        }
    }

}
